<template>
  <div class="create">
    
    <!--S侧边栏--> 
    <div class="sidebar" :class="sidebar ? 'show' : 'hide'">
      <cool-pages 
        :tpl-id="tpl_id"
        :init-complete="initComplete"
      >
      </cool-pages>
      <add-page></add-page>
    </div>
    <!--E侧边栏-->

    <!--S内容-->
    <div class="container">
      
      <!--Ssidebar显示隐藏按钮-->
      <div class="container__toggle" @click="toggleSidebar">
        页面管理
      </div>
      <!--Esidebar显示隐藏按钮-->

      
      <!--S顶部操作-->
      <div class="container__header">
        <div class="container__header-components">
          <top-components
            @change="mainComponentChange"
          >
          </top-components>
        </div>
        <div class="container__header-right">
          <right-top :tpl_id="tpl_id"></right-top>
        </div>
      </div>
      <!--E顶部操作-->


      <!--S操作内容-->
      <div class="container__handle">
        <cool-handle 
          :src="src"
          :tpl-id="tpl_id"
          :init-complete="initComplete"
          :ChilrenComponents="ChilrenComponents"
          @reset-handle="resetHandle"
        >
        </cool-handle>
      </div>
      <!--E操作内容-->

    </div>
    <!--E内容-->

  </div>
</template>

<script lang="ts">
import { ElMessage } from 'element-plus'
// 监听项目启动定时器
let listenProjectStatusTimer = null
// 监听项目启动的当前时间秒数
let listerProjectSecond = 0;
// 监听项目启动的最大秒数
let listerProjedctMax = 120;


import AddPage from './components/add-button/add-button.vue'
import RightTop from './components/Right-top/Right-top.vue'
import TopComponents from './components/top-components/top-components.vue'
import CoolHandle from './components/handle/handle.vue'
import CoolPages from './components/pages/pages.vue'

export default {
  name: "create",
  data() {
    return {
      // 模板项目id
      tpl_id: 0,
      //侧边栏是否显示
      sidebar: true,
      // 加载状态
      ElMessageResult: null,
      // tpm-uni-app地址
      src: '',
      // 项目页面数据
      pages: [],
      // 项目模板初始化是否完成
      initComplete: false
    }
  },
  components: {
    AddPage,
    RightTop,
    TopComponents,
    CoolHandle,
    CoolPages
  },
  computed: {
    // 侧边栏宽度
    sidebar_sapn() {
      return this.sidebar ? 3 : 0
    }
  },
  async unmounted() {
    this.ElMessageResult.close();
    await this.stopPort()
  },
  created() {
    this.tpl_id = this.$route.params.id
  },
  mounted() {
    this.showLoading()
    this.createProject()
  },
  methods: {
    /**
     * 显示进度
     */
    showLoading() {
      this.ElMessageResult = this.$loading({
        text: '首次初始化模板时间较长，请耐心等待...',
        customClass: 'loading-style'
      })
    },
    /**
     * 创建项目
     */
     async createProject() {
      // 1、先停止9288模板端口运行的程序
      await this.stopPort()

      // 2、先判断创建项目目录
      const { first_run } = await this.createDir()

      this.ElMessageResult.text = first_run ? "首次启动模板时间较长,请耐心等待..." : "模板启动中,请耐心等待...";

      // 3、开始运行项目
      await this.runPorject()
      
      // 4、设置uni-app项目地址
      clearInterval(listenProjectStatusTimer)
      listenProjectStatusTimer = setInterval(async () => {
        listerProjectSecond++;
        const result = await this.listenPorjectStatus()
        
        if(result) {
          this.ElMessageResult.close();
          this.src = "http://localhost:9288";
          this.initComplete = true
          clearInterval(listenProjectStatusTimer)
        } 
        
        if(!result && listerProjectSecond > listerProjedctMax) {
          ElMessage({
            message: "项目启动失败，请手动重新刷新页面",
            type: 'error',
            duration: 10000
          })
          this.ElMessageResult.close();
          clearInterval(listenProjectStatusTimer);
        }
      },1000)
    },
    /**
     * 创建项目目录
     */
    createDir() {
      return new Promise(async (resolve,reject) => {
        const res = await this.$post('tpl/create',{
          tpl_id: this.tpl_id
        })
          .then((res) => {
            resolve(res)
          })
          .catch((msg) => {
            reject(msg);
            ElMessage({
              message: msg,
              type: 'error'
            })
          })
      })
    },
    /**
     * 先停止模板项目运行的端口所有程序  端口号 9288
     */
    stopPort() {
      return new Promise((resolve,reject)=>{
        this.$post('port/stopPort')
          .then((res) => {
            resolve(true)
          })
          .catch((error) => {
            reject(false)
          })
      })
    },
    /**
     * 开始运行项目
     */
    runPorject() {
      return new Promise((reslove,reject)=>{
        this.$post("tpl/run",{
          tpl_id: this.tpl_id
        })
          .then((res) => {
            reslove(true)
          })
          .catch((error) => {
            reject()
          })
      })
    },
    /**
     * 定时器监听模板项目运行状态
     */
    listenPorjectStatus() {
      return new Promise((reslove,reject) => {
        this.$get('http://localhost:9288')
        .catch((error) => {
          if(error.response) {
            if(error.response.status == 404) {
              reslove(true);
            } else {
              reject(false);  
            }
          } else {
            reject(false);
          }
        })
      })
    },
    /**
     * 显示隐藏侧边栏
     */
    toggleSidebar() {
      this.sidebar = !this.sidebar
    },
    /**
     * 重启操作台
     */
    resetHandle() {
      this.showLoading()
      this.createProject()
    }
  }
}
</script>

<script lang="ts" setup>
  import { ref } from 'vue'
  let ChilrenComponents = ref([])
  /**
   * 主组件选择
   */
  const mainComponentChange = (res) => {
    ChilrenComponents.value = res
  }
</script>

<style>
  .loading-style .el-loading-text{ 
    color: #009d63;
  }
  .loading-style svg.circular .path{
    stroke: #009d63;
  }
</style>

<style scoped lang="scss">
.create{
  display: flex;
  height: 100vh;
  .sidebar{
    position: relative;
    width: 0;
    background-color: #ffffff;
    transition: .2s;
    overflow: hidden;
    box-shadow: 1px 0 10px rgba(0,0,0,.1);
    &.show{
      width: 12vw;
    }
    &.hide{
      width: 0;
    }
  }
  .container{
    transition: .2s;
    position: relative;
    flex: 1;
    display: flex;
    flex-direction: column;
    &__toggle{
      display: flex;
      align-items: center;
      position: absolute;
      top: 50%;
      left: 0;
      transform: translateY(-50%);
      width: 20px;
      height: 80px;
      padding-left: 3px;
      color:var(--second-text-color);
      font-weight: 600;
      font-size: 12px;
      cursor: pointer;
      line-height: 120%;
      user-select: none;
      border-radius: 0 10px 10px 0;
      box-shadow: 5px 0 5px 0 rgba(0,0,0,.1);
      background-color:#ffffff;
    }
    &__header{
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;
      box-sizing: border-box;
      width: 100%;
      height: 60px;
      background-color: var(--main-bg-color);
      color: var(--font-color);
      box-shadow: 5px 0 5px 0 rgba(0,0,0,.1);
      &-components{
        flex: 1;
      }
      &-right{
        width: 100px;
      }
    }
    &__handle{
      flex: 1;
      padding: 10px 10px 10px 30px;
      overflow: hidden;
    }
  }
}
</style>